<template>
  <div class="my-report-page">
    <!-- 头部导航 -->
    <div class="nav-header">
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
      <div class="title">我的上报</div>
      <div class="placeholder"></div>
    </div>

    <!-- 报告列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="loadMore"
      :immediate-check="false"
      :offset="50"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <div
        v-for="(report, index) in reportList"
        :key="index"
        class="report-item"
        @click="viewReportDetail(report)"
      >
        <!-- 地址信息 -->
        <div class="location-info">
          <van-icon name="location-o" color="#1989fa" />
          <span class="address">房屋地址：{{ report.address }}</span>
        </div>

        <!-- 时间信息 -->
        <div class="time-info">
          <van-icon name="clock-o" color="#969799" />
          <span class="time">上报时间：{{ report.reportTime }}</span>
        </div>

        <!-- 状态和操作按钮 -->
        <div class="action-area" @click.stop>
          <!-- 待确认状态 -->
          <div v-if="report.status === 'pending'" class="status-pending">
            <van-tag type="warning" plain class="status-tag">待确认</van-tag>
            <van-button
              plain
              round
              size="small"
              type="default"
              class="action-btn"
              @click="cancelReport(report)"
            >
              取消
            </van-button>
          </div>

          <!-- 处理中状态 -->
          <div
            v-else-if="report.status === 'processing'"
            class="status-processing"
          >
            <van-tag type="primary" plain class="status-tag">处理中</van-tag>
            <van-button
              size="small"
              round
              type="info"
              class="action-btn"
              @click="confirmComplete(report)"
            >
              确认完成
            </van-button>
          </div>

          <!-- 已完成状态 -->
          <div
            v-else-if="report.status === 'completed'"
            class="status-completed"
          >
            <van-tag type="success" plain class="status-tag">已完成</van-tag>
            <van-button
              plain
              round
              size="small"
              type="default"
              class="action-btn"
              @click="evaluateReport(report)"
            >
              评价
            </van-button>
          </div>
        </div>
      </div>
    </van-list>

    <!-- 空状态 -->
    <div v-if="reportList.length === 0 && !loading" class="empty-state">
      <van-empty
        image="https://img.yzcdn.cn/vant/custom-empty-image.png"
        description="暂无上报记录"
      />
    </div>

    <!-- 确认对话框 -->
    <van-dialog
      v-model="showConfirmDialog"
      title="确认操作"
      :message="confirmMessage"
      show-cancel-button
      @confirm="handleConfirm"
      @cancel="handleCancel"
    />
  </div>
</template>

<script>
export default {
  name: "MyReport",
  data() {
    return {
      reportList: [],
      loading: false,
      showConfirmDialog: false,
      confirmMessage: "",
      currentAction: null,
      currentReport: null,
      pageNum: 1,
      pageSize: 5,
      finished: false,
      total: 16,
      error: false,
      isRequesting: false, // 添加请求标志位
    };
  },

  async created() {
    await this.loadReportList();
  },

  methods: {
    goBack() {
      this.$router.go(-1);
    },

    // 加载上报列表
    async loadReportList() {
      try {
        // 模拟请求延迟
        await new Promise((resolve) => setTimeout(resolve, 500));
        await this.loadMockData();
      } catch (error) {
        this.error = true;
      } finally {
        this.loading = false;
      }
    },

    // 加载模拟数据
    async loadMockData() {
      // 生成所有模拟数据
      const allMockData = Array.from({ length: 16 }, (_, index) => ({
        id: index + 1,
        address: `10号楼${1000 + index}`,
        reportTime: `2025-11-${10 - Math.floor(index / 2)} ${14 + (index % 2)}:30`,
        status:
          index % 3 === 0
            ? "pending"
            : index % 3 === 1
              ? "processing"
              : "completed",
      }));

      // 根据当前页码获取对应的数据
      const start = (this.pageNum - 1) * this.pageSize;
      const end = start + this.pageSize;
      const pageData = allMockData.slice(start, end);

      // 如果是第一页，直接赋值，否则追加
      if (this.pageNum === 1) {
        this.reportList = pageData;
      } else {
        this.reportList = [...this.reportList, ...pageData];
      }

      // 判断是否加载完成
      if (this.reportList.length >= this.total) {
        this.finished = true;
      }
    },

    // 加载更多
    async loadMore() {
      if (this.finished) return;
      console.log("loadmore", this.loading, this.finished);

      try {
        // 模拟请求延迟
        await new Promise((resolve) => setTimeout(resolve, 500));

        // 生成所有模拟数据
        const allMockData = Array.from({ length: 16 }, (_, index) => ({
          id: index + 1,
          address: `10号楼${1000 + index}`,
          reportTime: `2025-11-${10 - Math.floor(index / 2)} ${14 + (index % 2)}:30`,
          status:
            index % 3 === 0
              ? "pending"
              : index % 3 === 1
                ? "processing"
                : "completed",
        }));

        // 根据当前页码获取对应的数据
        const start = (this.pageNum - 1) * this.pageSize;
        const end = start + this.pageSize;
        const pageData = allMockData.slice(start, end);

        // 如果是第一页，直接赋值，否则追加
        if (this.pageNum === 1) {
          this.reportList = pageData;
        } else {
          this.reportList = [...this.reportList, ...pageData];
        }

        // 判断是否加载完成
        if (this.reportList.length >= this.total) {
          this.finished = true;
        }

        // 增加页码
        this.pageNum += 1;
      } catch (error) {
        console.error("加载失败:", error);
      } finally {
        // 重置loading状态
        this.loading = false;
      }
    },

    cancelReport(report) {
      this.currentReport = report;
      this.currentAction = "cancel";
      this.confirmMessage = "确定要取消这个上报吗？";
      this.showConfirmDialog = true;
    },

    confirmComplete(report) {
      this.currentReport = report;
      this.currentAction = "complete";
      this.confirmMessage = "确认该问题已处理完成？";
      this.showConfirmDialog = true;
    },

    evaluateReport(report) {
      this.currentReport = report;
      // TODO: 后续跳转到评价页面
      this.$toast("跳转到评价页面");
    },

    async handleConfirm() {
      try {
        if (this.currentAction === "cancel") {
          // 取消上报 - 调用API
          await this.$api.report.deleteReport(this.currentReport.id);

          // 从列表中移除
          const index = this.reportList.findIndex(
            (item) => item.id === this.currentReport.id
          );
          if (index > -1) {
            this.reportList.splice(index, 1);
          }

          this.$toast.success("已取消上报");
        } else if (this.currentAction === "complete") {
          // 确认完成 - 调用API
          await this.$api.report.updateReport(this.currentReport.id, {
            status: "completed",
          });

          // 更新本地状态
          this.currentReport.status = "completed";
          this.$toast.success("已确认完成");
        }
      } catch (error) {
        console.error("操作失败:", error);
        this.$toast.fail(error.message || "操作失败");
      } finally {
        this.showConfirmDialog = false;
      }
    },

    handleCancel() {
      this.showConfirmDialog = false;
      this.currentAction = null;
      this.currentReport = null;
    },

    viewReportDetail(report) {
      // 跳转到白蚁上报详情页面
      this.$router.push({
        name: "termiteReportDetail",
        params: { id: report.id },
      });
    },
  },
};
</script>

<style scoped>
.my-report-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 头部导航样式 */
.nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 46px;
  background-color: #fff;
  border-bottom: 1px solid #ebedf0;
  padding: 0 16px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-icon {
  font-size: 20px;
  color: #323233;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.placeholder {
  width: 20px;
}

/* 报告列表样式 */
.report-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  position: relative;
  cursor: pointer;
  transition: all 0.2s ease;
}

.report-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-1px);
}

.report-item:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.location-info,
.time-info {
  display: flex;
  align-items: center;
  margin-bottom: 14px;
}

.location-info .van-icon,
.time-info .van-icon {
  margin-right: 8px;
  font-size: 14px;
}

.address {
  height: 15px;
  font-family:
    PingFangSC,
    PingFang SC;
  font-weight: 500;
  font-size: 15px;
  color: #333333;
  line-height: 15px;
}

.time {
  height: 12px;
  font-family:
    PingFangSC,
    PingFang SC;
  font-weight: 400;
  font-size: 12px;
  color: #999999;
  line-height: 12px;
}

.action-area {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #f5f5f5;
}

.status-pending,
.status-processing,
.status-completed {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
}

.status-tag {
  position: absolute;
  top: 0px;
  right: 0px;
  z-index: 10;
}

.action-btn {
  min-width: 70px;
  height: 32px;
}

/* 空状态样式 */
.empty-state {
  margin-top: 60px;
}

/* 评价弹窗样式 */
.evaluate-content {
  padding: 20px;
}

.evaluate-title {
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #323233;
}

.rate-section {
  margin-bottom: 20px;
}

.rate-label {
  font-size: 14px;
  color: #323233;
  margin-bottom: 12px;
}

.comment-section {
  margin-bottom: 20px;
}

.evaluate-buttons {
  display: flex;
  gap: 12px;
}

.evaluate-buttons .van-button {
  flex: 1;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

.finished-state {
  text-align: center;
  color: #969799;
  font-size: 14px;
  padding: 16px 0;
}
</style>
